//
//  MainPageViewController.m
//  TodayFirstNews
//
//  Created by 向祖华 on 16/3/1.
//  Copyright © 2016年 向祖华. All rights reserved.
//

#import "MainPageViewController.h"
#import "RecommendViewController.h"
#import "CarViewController.h"
#import "RegimenViewController.h"
#import "TravelViewController.h"
#import "AmazeViewController.h"
#import "HistoryViewController.h"
#import "EmotionViewController.h"
#import "SportViewController.h"
#import "FinanceViewController.h"
#import "PositiveEnergyViewController.h"
#import "HeathyViewController.h"
#import "MiliteryViewController.h"
#import "InternationViewController.h"
#import "EducationViewController.h"
#import "FoodViewController.h"
#import "HotspotViewController.h"
#import "VideoClassViewController.h"
#import "SocietyViewController.h"
#import "ScienceViewController.h"
#import "EntertainmentViewController.h"
#import "DrawViewController.h"
#import "TitleCollectionVC.h"

static CGFloat kSubtitleButtonHeigh = 44;
static CGFloat maxTitleScal = 1.3;


@interface MainPageViewController ()<UIScrollViewDelegate,TitleCollectionVCDelegate>
@property(nonatomic,strong)UIButton*selectedButton;
@property(nonatomic,strong)NSMutableArray * buttonArray;
@property(nonatomic,strong)NSMutableArray *arr;//当前页要显示的标题所存放的数组
@property(nonatomic,strong)NSDictionary * allTitleDic;//存放所有的标题的字典
@end

@implementation MainPageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //初始化所有标题的数组
    self.allTitleDic = @{@"推荐":@"RecommendViewController",@"汽车":@"CarViewController",@"养生":@"RegimenViewController",@"旅游":@"TravelViewController",@"奇葩":@"AmazeViewController",@"历史":@"HistoryViewController",@"情感":@"EmotionViewController",@"美图":@"RecommendViewController",@"福州":@"RecommendViewController",@"社会":@"SocietyViewController",@"娱乐":@"EntertainmentViewController",@"科技":@"ScienceViewController",@"段子":@"RecommendViewController",@"家居":@"RecommendViewController",@"时尚":@"RecommendViewController",@"语录":@"RecommendViewController",@"毕业生":@"RecommendViewController",@"彩票":@"RecommendViewController",@"正能量":@"PositiveEnergyViewController",@"军事":@"MiliteryViewController",@"订阅":@"RecommendViewController",@"趣图":@"RecommendViewController",@"美女":@"RecommendViewController",@"健康":@"RecommendViewController",@"特卖":@"RecommendViewController",@"精选":@"RecommendViewController",@"电影":@"VideoClassViewController",@"数码":@"RecommendViewController",@"辟谣":@"RecommendViewController",@"游戏":@"RecommendViewController",@"育儿":@"RecommendViewController",@"美食":@"FoodViewController",@"政务":@"RecommendViewController",@"探索":@"RecommendViewController",@"故事":@"RecommendViewController",@"美文":@"RecommendViewController",@"房产":@"RecommendViewController",@"搞笑":@"RecommendViewController",@"星座":@"RecommendViewController",@"文化":@"RecommendViewController",@"财经":@"FinanceViewController",@"国际":@"InternationViewController",@"教育":@"EducationViewController" ,@"热点":@"HotspotViewController",@"体育":@"SportViewController"};
    
    
#pragma mark - 处理存储标题的数组 arr
    //设置标题存放数组的初值（与titleCollectionVC界面的初值一样）
    self.arr = [NSMutableArray arrayWithObjects:@"推荐",@"星座",@"国际", nil];
    //
    //将初值数组与传值过来的数组进行去重融合
    if (self.titleArr.count) {
        //清空self.arr
        [self.arr removeAllObjects];
        //将传值过来的数组添加进去
        [self.arr addObjectsFromArray:self.titleArr];
    }
    //添加子控制器和Button
    [self addChildViewController];
    //设置代理
    self.contentScrollV.delegate = self;
    //设置展示界面
    UIButton * button = self.buttonArray[[self.clickIndex integerValue]];
    //调用点击button的事件
    [self buttonAction:button];
}
/**
 *  添加子控制器
 */
-(void)addChildViewController{
    //获取当前子控制器的所有标题
    NSMutableArray * keyArr = [[NSMutableArray alloc] init];
    for (BasicViewController * basicVC in self.childViewControllers) {
        [keyArr addObject:basicVC.title];
    }
    NSLog(@"原有子控制器数量:%lu",(unsigned long)keyArr.count);
    
    //循环删除没用的控制器和button
//    int count = (int)self.buttonArray.count;//获取当前子标题的控制器的个数
    for (int i = 0; i < (int)keyArr.count; i++) {
        if ([self.arr containsObject:keyArr[i]]) {
            continue;
        }
        else{
            //删除子控制器对应的view
            [self.contentScrollV.subviews[i] removeFromSuperview];
            //删除子控制器
            [self.childViewControllers[i] removeFromParentViewController];
            [keyArr removeObjectAtIndex:(NSInteger)i];
            //删除scrollView上的button
            [self.subtitleScrollV.subviews[i] removeFromSuperview];
            //删除按钮数组中的button
            [self.buttonArray removeObjectAtIndex:i];

            
            //删除控制器后就要处理界面
            //1.将后面的子控制器往前移
            [self moveAfterVCWithIndex:i viewControllerCount:(int)keyArr.count];
            //2.将Button标题往前移
            [self moveAfterButtonWithIndex:i buttonCount:(int)keyArr.count];
            //3.改变scrollView的尺寸
            [self changeCollectionViewSize];
            i--;
        }
    }
    //循环添加子控制器和按钮
    for (int i = 0; i < self.arr.count; i++) {
        //如果当前的子控制器标题数组中包含该标题，则不需要添加
        if ([keyArr containsObject:self.arr[i]]) {
            continue;
        }else{
            //创建控制器
            NSString*keyStr = self.arr[i];
            Class className = NSClassFromString(self.allTitleDic[keyStr]);
            BasicViewController * viewController = [[className alloc] init];
            //设置控制器的标题
            viewController.title = self.arr[i];
            //添加子控制器
            [self addChildViewController:viewController];
            //改变contentScrollV
            [self setContentScrollV];
            //添加view
            [self setControllerWithSelectedNumber:i];
            
            //改变subtitlescrollView/添加Button到按钮数组/subtitleScrollV
            [self setSubtitleScrollVWihtController:viewController index:i];
        }
    }
}
//改变子控制器的位置
-(void)moveAfterVCWithIndex:(int)index viewControllerCount:(int)count{
    for (int i = index; i < count;i++) {
        //获取控制器
        BasicViewController * VC = self.childViewControllers[i];
        //获取原来的frame
        CGRect  oldFrame = VC.view.frame;
        //改变frame-将后面的子控制器往前移一个屏幕的距离
        VC.view.frame = CGRectMake(oldFrame.origin.x-kScreenWidth, oldFrame.origin.y, oldFrame.size.width, oldFrame.size.height);
    }
}
//改变Button的位置
-(void)moveAfterButtonWithIndex:(int)index buttonCount:(int)count{
    for (int i = index; i < count; i++) {
        //获取到Button
        UIButton * button = self.buttonArray[i];
        //改变Button的tag值
        button.tag = i;
        //获取到原来的fram
        CGRect oldFram = button.frame;
        //改变fram-将后面的自控制器往前移一个屏幕的距离
        button.frame = CGRectMake(oldFram.origin.x - 70, 0, oldFram.size.width, oldFram.size.height);
    }
}
//改变collectionView的contentSize
-(void)changeCollectionViewSize{
    //获取原来的subtitleCollectionView的原尺寸
    CGSize subtitleSize = self.subtitleScrollV.contentSize;
    //改变size
    self.subtitleScrollV.contentSize = CGSizeMake(subtitleSize.width-70, subtitleSize.height);
    //获取原来的contentScrollV的原尺寸
    CGSize contentSize = self.contentScrollV.contentSize;
    //改变size
    self.contentScrollV.contentSize = CGSizeMake(contentSize.width-kScreenWidth, contentSize.height);
}


/**
 *  设置contentScrollV
 *
 */
-(void)setContentScrollV{
    //获取子控制器的数量即标题的数量
    NSInteger count = self.childViewControllers.count;
    //设置contentScrollV的尺寸
    self.contentScrollV.contentSize = CGSizeMake(kScreenWidth*count, 0);
    //设置不显示横向滑动条
    self.contentScrollV.showsHorizontalScrollIndicator = NO;
}
/**
 *  subtitleScrollV上添加button
 */
-(void)setSubtitleScrollVWihtController:(BasicViewController*)controller index:(NSInteger)index{
    CGFloat width = 70;//button的宽
    //获取子控制器的数量即标题的数量
    NSInteger count = self.childViewControllers.count;
    self.subtitleScrollV.showsHorizontalScrollIndicator = NO;
        //获取原来的subtitleScrollV的尺寸
        CGSize size = self.subtitleScrollV.contentSize;
        //改变subtitleScrollV的尺寸
        self.subtitleScrollV.contentSize = CGSizeMake(width*count, size.height);
        //添加button
        UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake(width*index, 0, width, kSubtitleButtonHeigh)];
        [button setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
        button.titleLabel.font = [UIFont systemFontOfSize:15];//字体大小

        [button setTitle:controller.title forState:(UIControlStateNormal)];
        button.tag = index;//tag值
        //点击事件
        [button addTarget:self action:@selector(buttonAction:) forControlEvents:(UIControlEventTouchUpInside)];
        if (index == 0) {
            [self buttonAction:button];
        }
        //将button添加到subtitleScrollV上
        [self.subtitleScrollV addSubview:button];
        //将button添加到按钮数组中
        [self.buttonArray addObject:button];
}
-(void)buttonAction:(UIButton*)button{
    //改变被选中的按钮fram
    [self buttonFramChange:button];
    NSInteger selectedButtonTag = button.tag;
    //添加或改变控制器
    [self setControllerWithSelectedNumber:selectedButtonTag];
    //设置contentScroll的显示位置
    self.contentScrollV.contentOffset = CGPointMake(selectedButtonTag*kScreenWidth, 0);
    //当前被点击按钮移动到中间位置
    [self setSubtitleScrollVAutomaticSlide:button];
}
/**
 *  将之前被选中的按钮恢复，并将被选中的按钮的颜色/字体进行改变
 *
 *  @param button 被选中的按钮
 */
-(void)buttonFramChange:(UIButton*)button{
    //对之前选中的按钮进行恢复
    [self.selectedButton setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
    self.selectedButton.titleLabel.font = [UIFont systemFontOfSize:15];
    self.selectedButton.transform = CGAffineTransformIdentity;
    //改变字体颜色及大小
    button.titleLabel.font = [UIFont systemFontOfSize:18];
    [button setTitleColor:[UIColor redColor] forState:(UIControlStateNormal)];
    //比例缩放1.3倍
    button.transform = CGAffineTransformMakeScale(maxTitleScal,maxTitleScal);
    self.selectedButton = button;
}
/**
 *  当点击对应按钮时，添加控制器
 *
 *  @param number 被点击的按钮tag值
 */
-(void)setControllerWithSelectedNumber:(NSInteger)number{
    //获取控制器
    UIViewController * vc = self.childViewControllers[number];
    //判断控制器是否已存在，存在则直接返回
    if (vc.view.superview) {
        return;
    }
    //设置位置大小
    vc.view.frame = CGRectMake(kScreenWidth*number,0, kScreenWidth, kScreenHeight-64);
    //添加到contentScrollV
    [self.contentScrollV addSubview:vc.view];
}
/**
 *  设置当前选中按钮在可显示的范围内
 *
 *  @param button被选中的按钮
 */
-(void)setSubtitleScrollVAutomaticSlide:(UIButton*)button{
    //获取按钮的位置
    CGFloat offset = button.center.x - kScreenWidth*0.5;
    if (offset < 0) {
        offset = 0;
    }
    if (offset > (self.subtitleScrollV.contentSize.width - kScreenWidth)) {
        offset = self.subtitleScrollV.contentSize.width - kScreenWidth;
    }
    //判断被选中的button的center.x值
    [self.subtitleScrollV setContentOffset:CGPointMake(offset, 0) animated:YES];
}
#pragma mark - 实现contentScrollV的代理方法
//减速结束
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    //获取当前contentScrollV的偏移量
    CGFloat currentOffset = self.contentScrollV.contentOffset.x;
    NSInteger i = currentOffset/kScreenWidth;//根据偏移获取当前显示界面对应按钮的下标
    //button跟随变化
    [self setSubtitleScrollVAutomaticSlide:self.buttonArray[i]];
    //加载对应的控制器
    [self setControllerWithSelectedNumber:currentOffset/kScreenWidth];
    self.selectedButton = self.buttonArray[i];
}
/**
 *  当scrollView滑动时，当前显示界面对应的按钮的大小和颜色，根据其对应界面的占屏比改变
 *
 *  @param scrollView 滑动的scrollview，这里指的是contentScrollV
 */
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    //获取当前界面contentScrollV的偏移量
    CGFloat offsetX = scrollView.contentOffset.x;
    //得到当前显示界面左边部分的view的下标
    NSInteger leftButtonIndex = offsetX/kScreenWidth;
    //得到右边view的下标
    NSInteger rightButtonIndex = leftButtonIndex + 1;
    //得到当前显示界面左边部分对应的button
    UIButton * leftButton = self.buttonArray[leftButtonIndex];
    //得到右边的Button
    UIButton * rightButton = nil;
    if (rightButtonIndex < self.buttonArray.count) {
        rightButton =  self.buttonArray[rightButtonIndex];
    }
    //左边按钮的变化依据
    CGFloat rightScale = offsetX/kScreenWidth - leftButtonIndex;
    //右边按钮的变化依据
    CGFloat leftScale = 1 - rightScale;
    CGFloat scale = maxTitleScal - 1;
    //改变左边的button的大小
    leftButton.transform = CGAffineTransformMakeScale(1 + scale*leftScale, 1 + scale*leftScale);
    //改变右边的button的大小
    rightButton.transform = CGAffineTransformMakeScale(1 + scale*rightScale, 1 + scale*rightScale);
    //改变左边的button的颜色
    [leftButton setTitleColor:[UIColor colorWithRed:leftScale green:0 blue:0 alpha:1] forState:(UIControlStateNormal)];
    //改变右边的button的颜色
    [rightButton setTitleColor:[UIColor colorWithRed:rightScale green:0 blue:0 alpha:1] forState:(UIControlStateNormal)];
    
}
#pragma mark - 实现titleCollectionVC的代理方法
-(void)sendTitleArr:(NSMutableArray *)array index:(NSInteger)index{
    self.titleArr = array;
    
    self.clickIndex = [NSNumber numberWithInteger:index];

    NSLog(@"代理方法内%@ index为：%ld",self.titleArr,(long)index);
    [self viewDidLoad];
}

//添加标题按钮的点击事件
- (IBAction)addTitleAction:(id)sender {
    //在storyBoard中找到对应的控制器
    TitleCollectionVC * titleVC = [self.storyboard instantiateViewControllerWithIdentifier:@"titleCollectionVC"];
    //记录当前界面的偏移量
    self.clickIndex =[NSNumber numberWithInteger: self.contentScrollV.contentOffset.x/kScreenWidth];
    NSLog(@"当前便宜位置%@",self.clickIndex );
    //传值
    [titleVC setValue:self.arr forKey:@"initialArr"];//传标题栏中的标题数组
    [titleVC setValue:self.clickIndex forKey:@"currentIndex"];//传当前显示的位置的button的下标值
    //跳转过去
    [self presentViewController:titleVC animated:YES completion:nil];
    titleVC.delegate = self;//设置titleVC的代理
}

#pragma mark - 懒加载
-(NSMutableArray *)buttonArray
{
    if (!_buttonArray) {
        _buttonArray = [[NSMutableArray alloc] init];
    }
    return _buttonArray;
}



-(NSArray *)titleArr{
    if (!_titleArr) {
        _titleArr = [[NSArray alloc] init];
    }
    return _titleArr;
}

-(NSMutableArray *)arr{
    if (!_arr) {
        _arr = [[NSMutableArray alloc] init];
    }
    return _arr;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
